package com.rjkj.medicalwaste.ui.collect

import android.app.Activity
import android.content.DialogInterface
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import com.rjkj.medicalwaste.MainActivity
import com.rjkj.medicalwaste.R
import com.rjkj.medicalwaste.adapter.CollectList2Adapter
import com.rjkj.medicalwaste.adapter.CollectListAdapter
import com.rjkj.medicalwaste.adapter.ItemClick
import com.rjkj.medicalwaste.base.BaseFragment
import com.rjkj.medicalwaste.base.addOneGarbage
import com.rjkj.medicalwaste.bean.*
import com.rjkj.medicalwaste.databinding.FragmentCollectMainBinding
import com.rjkj.medicalwaste.livedatabus.LiveDataBus
import com.rjkj.medicalwaste.utils.Encoder03Small
import com.rjkj.medicalwaste.utils.StringUtils
import com.rjkj.medicalwaste.utils.TimeUtils
import com.rjkj.medicalwaste.viewmodels.BluetoothControlViewModel
import com.rjkj.medicalwaste.viewmodels.CollectMainViewModel
import com.rjkj.medicalwaste.viewmodels.UserViewModel
import com.rjkj.medicalwaste.viewmodels.provider.MainViewModelProvider
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch


class CollectMainFragment : BaseFragment<FragmentCollectMainBinding>() {
    private val bluetoothControlViewModel: BluetoothControlViewModel by activityViewModels()
    private val userViewModel: UserViewModel by activityViewModels {
        MainViewModelProvider.provideUserModel(requireContext())
    }
    private val viewModel: CollectMainViewModel by activityViewModels {
        MainViewModelProvider.providerCollectMainModel(requireContext())
    }
    private lateinit var collectList2Adapter: CollectList2Adapter

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        val binding = FragmentCollectMainBinding.inflate(inflater, container, false)
        binding.lifecycleOwner = viewLifecycleOwner
        binding.userData = userViewModel
        binding.collectData = viewModel
        onSubscribeUi(binding)
        initKeyEvent()
        return binding.root
    }

    override fun dealCustomScanData(data: String) {
        super.dealCustomScanData(data)
        doScanCode(data)
    }

    override fun showAreYouSureDialog() {
        isExit()
    }

    override fun onSubscribeUi(binding: FragmentCollectMainBinding) {
        initTip(viewModel)
        initDialog(userViewModel)
        binding.imScan.setOnClickListener {
            scanWithCustomUI()
        }
        //管控箱数据拉取
        lifecycleScope.launch {
            viewModel.showLoading()
            val findPackByDepartment =
                viewModel.findPackByDepartment(
                    userViewModel.getUrl(),
                    listOf(userViewModel.departmentUser.value!!.qrcode)
                )
            viewModel.addGarbageListToList(findPackByDepartment.map { pack ->
                val nurse = userViewModel.findUserByQrCode(pack.personQRCode1)
                    ?: UserBean(qrcode = pack.personQRCode1)
                val cleaner = userViewModel.findUserByQrCode(pack.personQRCode2)
                    ?: UserBean(qrcode = pack.personQRCode2)
                val department = userViewModel.findUserByQrCode(pack.departmentQRCode)
                    ?: UserBean(qrcode = pack.departmentQRCode)
                addOneGarbage(
                    pack.garbageQRCode,
                    pack.garbageWeight,
                    MedicalWasteType.getTypeByTypeName(pack.garbageType),
                    pack.hospitalId,
                    department.hospitalName,
                    cleaner,
                    nurse,
                    department,
                    userViewModel.getSerial(),
                    fromControlBox = true
                )

            })
            viewModel.closeLoading()
        }
        lifecycleScope.launchWhenResumed {
            userViewModel.departmentClock(
                value = DepartmentClockReq(
                    deviceSN = userViewModel.getSerial(),
                    cleanerQRCode = userViewModel.cleanerUser.qrcode,
                    clockTime = TimeUtils.getYMDHMSTime(),
                    departmentQRCode = userViewModel.departmentUser.value?.qrcode ?: ""
                )
            )
        }
        viewModel.list.observe(viewLifecycleOwner, { value ->
            lifecycleScope.launchWhenResumed {
                if (value.isNotEmpty()) {
                    binding.imEmpty.visibility = View.GONE
                } else {
                    binding.imEmpty.visibility = View.VISIBLE
                }
                collectList2Adapter.list = value
                collectList2Adapter.notifyDataSetChanged()
            }
        })
        if (userViewModel.setting.value!!.prefabricatedLabel) {
            LiveDataBus.get().with(MainActivity.SCAN_DATA, String::class.java).observe(
                viewLifecycleOwner, {
                    doScanCode(it)
                }
            )
        }
        collectList2Adapter = CollectList2Adapter(
            viewModel.list.value!!,
            requireContext(),
            object : ItemClick<GarbageBean> {
                override fun onClicked(view: View, value: GarbageBean) {
                    if (userViewModel.setting.value!!.prefabricatedLabel) {
                        //预制标签
                        showDeleteDialog(value)
                    } else {
                        showPrintAndDeleteDialog(value)
                    }
                }
            })
        binding.imBack.setOnClickListener {
            requireActivity().onBackPressed()

        }
        binding.btCollect.setOnClickListener {
            if (userViewModel.setting.value!!.prefabricatedLabel) {
                //预制标签
                showTip("请扫入预制标签")
            } else {
                findNavController().navigate(R.id.action_collectMainFragment_to_collectOneFragment)
            }

        }
        binding.list.apply {
            layoutManager = LinearLayoutManager(requireContext())
            adapter = collectList2Adapter
        }
        binding.btPrint.setOnClickListener {
            handover()
        }
    }

    private fun doScanCode(it: String) {
        lifecycleScope.launchWhenResumed {
            if (it.length == 49) {
                val split = it.split("?")
                if (split.size == 2 && StringUtils.checkTagRealness(split[1])) {
                    val code = "1" + split[1]
                    val findGarbageByCode2 =
                        viewModel.garbageRepository.findGarbageByCode2(code)
                    if (findGarbageByCode2 == null) {
                        val value = viewModel.list.value
                        if (value?.contains(GarbageBean(garbageQRCode = code)) == true) {
                            showHaveOneDialog(split[1])
                        } else {
                            goToCollectFragment2(split[1])
                        }
                    } else {
                        showTip("已存在该预制标签医废")
                    }


                }
            }
        }
    }

    private fun goToCollectFragment2(code: String) {
        val actionCollectMainFragment =
            if (userViewModel.setting.value?.infoMode == 1) {
                CollectMainFragmentDirections.actionCollectMainFragmentToCollectOneFragment3(
                    code
                )
            } else {
                CollectMainFragmentDirections.actionCollectMainFragmentToCollectOneFragment2(
                    code
                )
            }
        findNavController().navigate(
            actionCollectMainFragment
        )
    }

    /**
     * 交接收集的医废
     */
    private fun handover() {
        val value = viewModel.list.value!!
        if (value.isNotEmpty()) {
            lifecycleScope.launch {
                userViewModel.uploadEvent.value = (true)
                bluetoothControlViewModel.printHandoverInfo(
                    cleaner = userViewModel.cleanerUser,
                    department = userViewModel.departmentUser.value!!,
                    nurse = userViewModel.nurseUser.value!!,
                    value,
                    userViewModel.setting.value?.printItemList ?: listOf()
                )
                viewModel.printGarbageList()
                runCatching {
                    Log.e(TAG, "addAllGarbageToDatabase: ${value.toString()}")
                    viewModel.addAllGarbageToDatabase(value)
                }.onSuccess {
                    userViewModel.uploadGarbage(
                        garbageBeanList = value,
                        successState = GarbageBean.collectState,
                        failState = GarbageBean.nullState
                    )
                    userViewModel.uploadEvent.value = (false)
                    showTip("交接成功")
                    delay(1500)
                    findNavController().navigateUp()
                }.onFailure {
                    userViewModel.uploadEvent.value = (false)
                    showTip("交接失败")
                }


            }
        } else {
            showTip("没有可以交接的数据")
            return
        }
    }


    private fun rePrint(garbageBean: GarbageBean) {

        lifecycleScope.launch(Dispatchers.IO) {
            val format = String.format("%04d", garbageBean.garbageWeight.replace(".", "").toInt())
            val serialNum = userViewModel.getSerial()
            Log.e(TAG, "addGarbage:$serialNum ")
            val garbageQRCode = "1" +
                    TimeUtils.getYYMMDDHHMMSS(garbageBean.garbageTime) +
                    serialNum +
                    MedicalWasteType.getTypeByTypeName(garbageBean.garbageType).num.toString() +
                    format +
                    garbageBean.departmentQRCode.substring(12) +
                    garbageBean.nurseQRCode.substring(12) +
                    garbageBean.cleanerQRCode.substring(12) +
                    "B"
            val encoder03Small = Encoder03Small()
            //袋模式1，箱模式：2
            encoder03Small.setQRcode("1", garbageQRCode, userViewModel.hospitalId.value)
            encoder03Small.setGarbage(
                userViewModel.hospitalName.value,
                garbageBean.departmentName,
                garbageBean.garbageWeight + "KG",
                garbageBean.garbageType,
                garbageBean.cleanerName,
                garbageBean.nurseQRName,
                garbageBean.garbageTime
            )
            bluetoothControlViewModel.printRec(encoder03Small)

        }
    }

    private fun showHaveOneDialog(code: String) {
        AlertDialog.Builder(requireContext()).apply {
            setTitle("已存在该预制标签，是否覆盖？")
            setPositiveButton("确定") { _: DialogInterface, _: Int ->
                goToCollectFragment2(code)
            }
            setNegativeButton("关闭") { _: DialogInterface, _: Int ->

            }
        }.show()
    }

    private fun showPrintAndDeleteDialog(value: GarbageBean) {
        AlertDialog.Builder(requireContext()).apply {
            val strings = arrayOf("重新打印", "删除该医废")
            setTitle("${value.garbageType}:${value.garbageWeight}千克")
            setItems(strings) { _: DialogInterface, i: Int ->
                when (i) {
                    0 -> {
                        rePrint(value)
                    }
                    1 -> {
                        viewModel.deleteGarbage(value)
                    }
                }
            }
            setNegativeButton("关闭") { _: DialogInterface, _: Int ->

            }
        }.show()
    }

    private fun showDeleteDialog(value: GarbageBean) {
        AlertDialog.Builder(requireContext()).apply {
            val strings = arrayOf("删除该医废")
            setTitle("${value.garbageType}:${value.garbageWeight}千克")
            setItems(strings) { _: DialogInterface, i: Int ->
                when (i) {
                    0 -> {
                        viewModel.deleteGarbage(value)
                    }
                }
            }
            setNegativeButton("关闭") { _: DialogInterface, _: Int ->

            }
        }.show()
    }

    private fun showPrintDialog(value: GarbageBean) {
        AlertDialog.Builder(requireContext()).apply {
            val strings = arrayOf("重新打印")
            setTitle("${value.garbageType}:${value.garbageWeight}千克")
            setItems(strings) { _: DialogInterface, i: Int ->
                rePrint(value)
            }
            setNegativeButton("关闭") { _: DialogInterface, _: Int ->
            }
        }.show()
    }
}